package cn.iocoder.yudao.module.system.jgpush;

import cn.jiguang.sdk.api.PushApi;
import feign.Client;
import feign.Logger;
import feign.Request;
import feign.Retryer;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class PushApiFactory {

    private static String appKey;

    private static String masterSecret;

    private static volatile PushApi pushApiInstance;

    @Value("${jg.AppKey}")
    public void setAppKey(String key) {
        PushApiFactory.appKey = key;
    }
    @Value("${jg.MasterSecret}")
    public void setMasterSecret(String masterSecret) {
        PushApiFactory.masterSecret = masterSecret;
    }

    // 私有构造函数防止外部实例化
    private PushApiFactory() {}

    public static PushApi getInstance() {
        if (pushApiInstance == null) {
            synchronized (PushApiFactory.class) {
                if (pushApiInstance == null) {
                    pushApiInstance = buildPushApi(appKey, masterSecret);
                }
            }
        }
        return pushApiInstance;
    }

    private static PushApi buildPushApi(String appKey, String masterSecret) {
        // 自定义底层 OkHttpClient 配置连接池和超时
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(50, 5, TimeUnit.MINUTES))
                .build();

        Client client = new feign.okhttp.OkHttpClient(okHttpClient);

        // 配置请求选项（超时设置）
        Request.Options options = new Request.Options(
                5000,   // 连接超时时间（毫秒）
                10000   // 读取超时时间（毫秒）
        );

        // 配置重试策略（不重试）
        Retryer retryer = Retryer.NEVER_RETRY;

        // 使用 PushApi 的 Builder 构建 PushApi 实例
        PushApi pushApi = new PushApi.Builder()
                .setAppKey(appKey)
                .setMasterSecret(masterSecret)
                .setClient(client)        // 设置自定义的 Feign Client
                .setOptions(options)      // 设置超时选项
                .setRetryer(retryer)      // 设置重试策略
                .setLoggerLevel(Logger.Level.FULL)  // 设置日志级别
                .build();

        return pushApi;
    }
}